package dk.viauc.friendlocator;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.maps.model.LatLng;

public class WebServiceUpdate extends
		AsyncTask<FriendLocation, String, ArrayList<FriendLocation>> {
	
	StringBuilder builder = new StringBuilder();
	ArrayList<FriendLocation> friends;
	Context context;
	
	public WebServiceUpdate(Context context) {
		this.context = context;
	}
	
	@Override
	protected ArrayList<FriendLocation> doInBackground(FriendLocation... params) {
		JSONObject json = new JSONObject();
		try {
			json.put("myName", params[0].getName());
			json.put("myLatitude", params[0].getLocation().latitude + "");
			json.put("myLongitude", params[0].getLocation().longitude + "");
			json.put("date", params[0].getDate());
			
			HttpClient client = new DefaultHttpClient();
			HttpPost request = new HttpPost(Globals.WEB_SERVICE_URL);
			request.setEntity(new StringEntity(json.toString()));
			request.setHeader("Content-Type", "application/json");
			request.setHeader("Accept", "application/json");
			
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
				JSONObject jObj = new JSONObject(builder.toString());
				friends = parseJson(jObj);
			}
			else {
				Log.e(getClass().getSimpleName(), "Could not contact WebService. Status: " + response.getStatusLine().getStatusCode(), null);
				Toast.makeText(context, "Could not contact WebService", Toast.LENGTH_LONG).show();
			}

		} catch (Throwable e) {
			Log.e(getClass().getSimpleName(), "Could not contact WebService", e);
			Toast.makeText(context, "Could not contact WebService", Toast.LENGTH_LONG).show();
		}
		return friends;
	}
	
	private ArrayList<FriendLocation> parseJson(JSONObject json) {
		ArrayList<FriendLocation> arr = new ArrayList<FriendLocation>();
		JSONObject location;
		try {
			JSONArray jArray = json.getJSONArray("d");
			for (int i = 0; i < jArray.length(); i++) {
				JSONObject friend = (JSONObject) jArray.get(i);
				String name = friend.getString("name");
				String date = friend.getString("date");
				location = friend.getJSONObject("location");
				double longitude = location.getDouble("longitude");
				double latitude  = location.getDouble("latitude");
				arr.add(new FriendLocation(name, new LatLng(latitude, longitude), date));
			}
		} catch (JSONException e) {
			Log.e(getClass().getSimpleName(), "Error parsing JSON", e);
		}
		return arr;
	}

}


